package com.docker.fy.service.impl;

import com.docker.fy.mapper.*;
import com.docker.fy.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 23118
 * @version 1.0
 * @description: TODO
 * @date 2025/4/14 14:03
 */
@Service
public class PatientServiceImpl implements PatientService {

    @Autowired
    private FyPrescriptionMapper prescriptionMapper;
    @Autowired
    private FyInspectMapper inspectMapper;
    @Autowired
    private FyOrderMapper orderMapper;
    @Autowired
    private FyDoctorMapper doctorMapper;
    @Autowired
    private FyDeptMapper deptMapper;
    @Autowired
    private FyPrescriptionMedicineMapper prescriptionMedicineMapper;
    @Autowired
    private FyDockerDrugMapper dockerDrugMapper;
    @Override
    public List<Map> getInfoByPatientId(Long patient_id) {
        //所有信息的集合
        List<Map> result = new ArrayList<>();
        //1先根据患者id获取处方信息
        List<Map> prescription = getPrescriptionByPatientId(patient_id);
//        System.out.println(prescription);
        //格式化时间为yyyy-MM-dd HH:mm:ss
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //处方id
        for (Map prescriptionMap : prescription) {
//            System.out.println(prescriptionMap);
            //封装信息
            Map resultMap = new HashMap<>();

            //获取处方id
            int prescription_id = (Integer) prescriptionMap.get("prescription_id");
//            System.out.println(prescription_id);
            //获取开处方时间
            LocalDateTime time = (LocalDateTime) prescriptionMap.get("time");
            if (time != null){
                //格式化时间为yyyy-MM-dd HH:mm:ss
                String timeOpen = time.format(formatter);
//            System.out.println(time);
                //开处方的时间
                resultMap.put("time", timeOpen);
            }

            //封装诊断信息
            resultMap.put("diagnosis",prescriptionMap.get("diagnosis"));
            //2根据开处方时间和患者id获取病历信息
            Map medicalRecordInfo = getMedicalRecord(patient_id,time);
//            System.out.println(medicalRecordInfo);

            //封装病历信息
            Map physicalInfo = new HashMap<>();
            if (medicalRecordInfo == null) {
                //如果病历信息为空,封装空信息
                physicalInfo.put("temperature","");
                physicalInfo.put("breathing","");
                physicalInfo.put("pulse","");
                physicalInfo.put("bloodPressure","");
                physicalInfo.put("bloodSugar","");
                physicalInfo.put("bloodFat","");
                physicalInfo.put("height","");
                physicalInfo.put("weight","");
            }
            else {
                //如果病历信息不为空,封装病历信息
                //体温
                physicalInfo.put("temperature",medicalRecordInfo.get("body_temperature"));
                //呼吸
                physicalInfo.put("breathing",medicalRecordInfo.get("respiration"));
                //脉搏
                physicalInfo.put("pulse",medicalRecordInfo.get("pluses"));
                //血压
                physicalInfo.put("bloodPressure",medicalRecordInfo.get("blood_pressure"));
                //血糖
                physicalInfo.put("bloodSugar",medicalRecordInfo.get("blood_glucose"));
                //血脂
                physicalInfo.put("bloodFat",medicalRecordInfo.get("blood_lipid"));
                //身高
                physicalInfo.put("height",medicalRecordInfo.get("height"));
                //体重
                physicalInfo.put("weight",medicalRecordInfo.get("weight"));
                //封装病史信息
                Map medicalInfo = new HashMap<>();
                //发病时间
                LocalDateTime onset_date = (LocalDateTime)medicalRecordInfo.get("onset_date");

                String formattedDate = onset_date.format(formatter);
//                System.out.println(formattedDate);
                medicalInfo.put("onsetDate",formattedDate);
                //主诉
                medicalInfo.put("mainComplaint",medicalRecordInfo.get("complaints_info"));
                //现病史
                medicalInfo.put("presentIllness",medicalRecordInfo.get("present_illness"));
                //既往史
                medicalInfo.put("pastHistory",medicalRecordInfo.get("medical_history"));
                //过敏史
                medicalInfo.put("allergyHistory",medicalRecordInfo.get("allergic_history"));
                //个人史
                medicalInfo.put("personalHistory",medicalRecordInfo.get("personal_history"));
                //家族史
                medicalInfo.put("familyHistory",medicalRecordInfo.get("family_history"));
                //辅助检查
                medicalInfo.put("auxiliaryExam",medicalRecordInfo.get("auxiliary_examination"));
                //治疗意见
                medicalInfo.put("treatmentAdvice",medicalRecordInfo.get("treatment_advice"));
                //备注
                medicalInfo.put("remarks",medicalRecordInfo.get("remark"));
                //保存到resultMap中
                resultMap.put("physicalInfo",physicalInfo);
                resultMap.put("medicalInfo",medicalInfo);
            }

            //3根据处方id查询订单信息
            Map orderInfo = getOrderInfo(prescription_id);
//            System.out.println(orderInfo);
            //4根据订单id获取医生id，再根据医生id查询医生信息
            if (orderInfo != null) {
                int doctorId = (Integer) orderInfo.get("doctor_id");
                Map map = getDoctorInfo(doctorId);
//                System.out.println(map);
                //封装医生姓名和科室
                if (map!= null) {
                    resultMap.put("department",map.get("deptName"));
                    resultMap.put("doctor",map.get("user_name"));
                }else {
                    resultMap.put("department","");
                    resultMap.put("doctor","");
                }
            }
            //5根据处方id去查询处方药品中间表，再根据药品id查询药品信息
            List<Map> medicineInfo = getPrescriptionMedicineInfo(prescription_id);
//            System.out.println(medicineInfo);
            //封装药品信息
            List<Map> prescriptions = new ArrayList<>();
            for (Map medicineMap : medicineInfo) {
//                System.out.println(medicineMap);
                Map prescriptionMedicineMap = new HashMap<>();
                //药品名称
                prescriptionMedicineMap.put("name",medicineMap.get("drug_generic_name"));
                //药品规格
                prescriptionMedicineMap.put("drug_specification",medicineMap.get("drug_specification"));
                //频度
                prescriptionMedicineMap.put("frequency",medicineMap.get("frequency"));
                //数量
                prescriptionMedicineMap.put("quantity",medicineMap.get("medicine_num"));
                //保存到prescriptions中
                prescriptions.add(prescriptionMedicineMap);
            }
            //保存到resultMap中
            resultMap.put("prescriptions",prescriptions);
            //保存到result中
            result.add(resultMap);
        }
//        System.out.println(result);
        return result;
    }

    private List<Map> getPrescriptionMedicineInfo(int prescription_id) {
        List<Map> result = new ArrayList<>();
        //根据处方id查询处方药品中间表
        List<Map> prescriptionMedicineInfo = prescriptionMedicineMapper.getPrescriptionMedicineInfoByPrescriptionId(prescription_id);
        if (prescriptionMedicineInfo != null) {
            //遍历处方药品中间表获取药品id
            prescriptionMedicineInfo.forEach(map -> {
                //获取药品id
                int medicine_id = (Integer) map.get("medicine_id");
                //获取药品数量
                int medicine_num = (Integer) map.get("number");
                //根据药品id查询药品信息
                Map dockerDrugMap = dockerDrugMapper.getDockerDrugInfoByDrugId(medicine_id);
                //封装信息
                if (dockerDrugMap!= null) {
                    dockerDrugMap.put("medicine_num", medicine_num);
                    result.add(dockerDrugMap);
                }
            });
        }
        return result;
    }

    private Map getDoctorInfo(int doctorId) {
        //根据医生id查询医生信息
        Map map = doctorMapper.getDoctorInfoByDoctorId(doctorId);
        if (map != null) {
            //获取部门id
            Long department_id = (Long) map.get("dept_id");
            //根据部门id查询部门名称
            String deptName = deptMapper.getDeptNameByDeptId(department_id);
            //保存到map中
            map.put("deptName", deptName);
        }
        return map;
    }

    private Map getOrderInfo(int prescription_id) {
        Map orderMap = orderMapper.getOrderInfoByPrescriptionId(prescription_id);
        return orderMap;
    }

    private Map getMedicalRecord(Long patient_id, LocalDateTime time) {
        Map map = inspectMapper.getMedicalRecordInfoBypatientIdAndCreateTime(patient_id,time);
        return map;
    }

    private List<Map> getPrescriptionByPatientId(Long patient_id) {
        List<Map> prescription = prescriptionMapper.getPrescriptionByPatientId(patient_id);
        List<Map> result = new ArrayList<>();
        for (Map map : prescription) {
            Map prescriptionMap = new HashMap<>();
            //获取处方id
            int prescription_id = (Integer) map.get("id");
            prescriptionMap.put("prescription_id", prescription_id);
            //开处方时间
            LocalDateTime time = (LocalDateTime) map.get("create_time");
//            System.out.println(time);
            prescriptionMap.put("time", time);
            //诊断
            String diagnosis = (String) map.get("diagnosis");
            prescriptionMap.put("diagnosis", diagnosis);
            //医嘱
            String advice = (String) map.get("advice");
            prescriptionMap.put("remarks", advice);
            //保存到result中
            result.add(prescriptionMap);
        }
        return result;
    }



}
